package sf.database.jdbc.type;

import java.io.InputStream;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

/**
 * sqlite 不支持blob类型
 */
public class BlobType implements TypeHandler<Blob> {

    public Blob get(ResultSet rs, String columnName) throws SQLException {
        return rs.getBlob(columnName);
    }

    public Blob get(ResultSet rs, int index) throws SQLException {
        return rs.getBlob(index);
    }

    public Blob get(CallableStatement rs, int index) throws SQLException {
        return rs.getBlob(index);
    }

    @Override
    public Blob get(CallableStatement cs, String parameterName) throws SQLException {
        return cs.getBlob(parameterName);
    }

    public Object set(PreparedStatement ps, Object obj, int i) throws SQLException {
        if (null == obj) {
            ps.setNull(i, getSqlType());
        } else {
            if (Blob.class.isAssignableFrom(obj.getClass())) {
                ps.setBlob(i, (Blob) obj);
            } else if (InputStream.class.isAssignableFrom(obj.getClass())) {
                ps.setBlob(i, (InputStream) obj);
            }
        }
        return null;
    }

    @Override
    public Object set(CallableStatement cs, Object obj, String parameterName) throws SQLException {
        if (null == obj) {
            cs.setNull(parameterName, getSqlType());
        } else {
            if (Blob.class.isAssignableFrom(obj.getClass())) {
                cs.setBlob(parameterName, (Blob) obj);
            } else if (InputStream.class.isAssignableFrom(obj.getClass())) {
                cs.setBlob(parameterName, (InputStream) obj);
            }
        }
        return null;
    }

    @Override
    public void update(ResultSet rs, String columnLabel, Object value) throws SQLException {
        if (Blob.class.isAssignableFrom(value.getClass())) {
            rs.updateBlob(columnLabel, (Blob) value);
        } else if (InputStream.class.isAssignableFrom(value.getClass())) {
            rs.updateBlob(columnLabel, (InputStream) value);
        }
    }

    @Override
    public void update(ResultSet rs, int columnIndex, Object value) throws SQLException {
        if (Blob.class.isAssignableFrom(value.getClass())) {
            rs.updateBlob(columnIndex, (Blob) value);
        } else if (InputStream.class.isAssignableFrom(value.getClass())) {
            rs.updateBlob(columnIndex, (InputStream) value);
        }
    }

    public int getSqlType() {
        return Types.BLOB;
    }

    @Override
    public Class<Blob> getDefaultJavaType() {
        return Blob.class;
    }
}